using RealtimeCollabGame.Application.Interfaces;
using RealtimeCollabGame.Application.Queries;
using RealtimeCollabGame.Application.DTOs;

namespace RealtimeCollabGame.Application.Handlers;

public class GetAllGamesQueryHandler
{
    private readonly IGameRepository _gameRepository;

    public GetAllGamesQueryHandler(IGameRepository gameRepository)
    {
        _gameRepository = gameRepository;
    }

    public async Task<List<GameDto>> HandleAsync(GetAllGamesQuery query)
    {
        var games = await _gameRepository.GetAllAsync();

        return games.Select(game =>
        {
            return new GameDto(
                game.Id,
                game.Name,
                game.Code,
                game.Status,
                game.MaxPlayers,
                game.Players.Count,
                game.GameDuration,
                game.StartedAt,
                game.EndedAt,
                game.GetTimeLeft(),
                game.HasPassword,
                game.Players.Select((p, index) => new PlayerDto(
                    p.Id,
                    p.NickName,
                    p.Avatar,
                    p.Color.Value,
                    p.IsOnline,
                    p.LastActiveAt,
                    index == 0, // 第一个玩家作为房主
                    p.IsReady
                )).ToList(),
                game.Canvas.Width,
                game.Canvas.Height
            );
        }).ToList();
    }
}